package com.moliku.insurance.process.listener;

import com.alibaba.fastjson.JSON;
import com.moliku.insurance.common.constant.BusinessEnum;
import com.moliku.insurance.common.constant.CompanyEnum;
import com.moliku.insurance.model.dto.CancelInsureDTO;
import com.moliku.insurance.model.dto.MessageDTO;
import com.moliku.insurance.model.dto.insure.InsureDTO;
import com.moliku.insurance.process.strategy.PolicyStrategy;
import com.moliku.insurance.process.strategy.StrategyFactory;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;

/**
 * Rocket 消息监听
 * Tags 区分业务
 * MessageDTO 中 company属性区分不同的公司
 *
 * @author Mr.Liu
 * @since 2021/2/5
 */
@Slf4j
@Component
@AllArgsConstructor
// @RocketMQMessageListener(consumerGroup = "${rocketmq.consumer.group}", topic = "${rocketmq.topic}")
public class RocketListener implements RocketMQListener<MessageExt> {

    private final StrategyFactory strategyFactory;

    @Override
    public void onMessage(MessageExt message) {
        //解析消息内容
        MessageDTO messageDTO = JSON.parseObject(new String(message.getBody(), StandardCharsets.UTF_8), MessageDTO.class);
        String company = messageDTO.getCompany();
        String business = message.getTags();
        String data = messageDTO.getData();

        if (StringUtils.isBlank(business) || StringUtils.isBlank(company) || StringUtils.isBlank(data)) {
            log.warn("空数据消息");
            return;
        }
        //查询消息消费记录

        //消息消费过

        //消息没有消费过

        //业务处理
        log.info("公司：{}={}", company, CompanyEnum.getName(company));
        log.info("业务：{}={}", business, BusinessEnum.getName(business));
        log.info("数据：{}", data);
        PolicyStrategy strategy = strategyFactory.getInstance(company);

        if (BusinessEnum.SUBMIT_POLICY.getCode().equals(business)) {
            log.info("处理投保业务");
            InsureDTO insure = JSON.parseObject(data, InsureDTO.class);
            strategy.submitPolicy(insure);
        } else if (BusinessEnum.CANCEL_POLICY.getCode().equals(business)) {
            log.info("处理退保业务");
            CancelInsureDTO cancelInsure = JSON.parseObject(data, CancelInsureDTO.class);
            strategy.cancelPolicy(cancelInsure);
        } else {
            log.warn("消息业务标签不匹配");
        }

        // 记录消息消费日志

    }
}
